from pathlib import Path
from splinter import Browser
import time
import platform
from tool import storage, util, dbutil
from manager import Manager
import config

CookiesKey = "CookiesKey"

LoginURL = 'https://mp.yuncheapp.cn/admin/html/media/login.html'
HomeURL = "https://mp.yuncheapp.cn/admin/html/media/summary.html"

PublishURL = "https://mp.yuncheapp.cn/admin/html/media/works/publish.html"


def open(name, pwd, videos=None):
    if videos is None or len(videos) == 0:
        consolewrap('上传的视频为空')
        return
    consolewrap('准备上传看点用户：' + name)

    headless = True

    driverpath = ''
    if platform.system() == 'Windows':
        driverpath = './Source/win/chromedriver.exe'
    else:
        driverpath = './Source/mac/chromedriver'

    with Browser('chrome', executable_path=driverpath, headless=headless) as browser:

        cookieDic = storage.getValue(CookiesKey)
        if cookieDic == None:
            cookies = login(name, pwd, browser)
        else:
            if name in cookieDic.keys():
                cookies = cookieDic[name]
            else:
                cookies = login(name, pwd, browser)

        browser.visit(HomeURL)
        if cookies != None:
            browser.cookies.add(cookies)

        for video in videos:
            start(browser, video)


def start(browser, video):
    # video.path 相对路径
    # path 为绝对路径
    path = str(Path(video.path).absolute())
    if path is None or path == None:
        consolewrap('上传的视频为空')
        return
    title = video.title
    summary = video.title
    tags = video.tags.split(",")
    # 标题5-30
    if len(title) > 30:
        title = title[0:30]

    if tags == None or len(tags) == 0:
        # 分词
        tags = util.participle_list(title)
    if len(tags) > 5:
        tags = tags[:5]

    browser.visit(PublishURL)

    # 视频创作
    browser.find_by_text("视频创作").first.click()

    browser.find_by_xpath(
        '//input[@type="file"]').first.fill(path)

    ele = getElementByTextWithTime(browser, "上传成功", 200)
    if ele is None:
        return
    # 上传成功
    # 标题
    if title != None and len(title) > 0:
        browser.find_by_id('title').first.fill(title)
    # 封面
    consolewrap("设置封面...")
    browser.find_by_xpath(
        '//div[@class="coverContainer___1t_6Y"]').first.click()

    consolewrap("设置图片 下一步...")
    next_element =  getElementByTextWithTime(browser, "下一步")
    consolewrap("加载图片中...")
    is_enabledWithTime(next_element)
    next_element.click()
    time.sleep(1)

    # 图片裁剪 doCrop___1KO-j
    if isElementExist(browser, '//div[@class="doCrop___1KO-j"]'):
        elem = browser.find_by_xpath('//div[@class="doCrop___1KO-j"]').first
        if elem.visible:
            consolewrap("裁剪图片...")
            elem.click()
            time.sleep(1)

    consolewrap("设置图片 开始点击确认")
    getElementByTextWithTime(browser, "确 认").click()
    consolewrap("设置图片 确定完成")

    # 封面图片
    imgEle = getElementByXpathWithTime(
        browser, '//img[@class="cover___e2z5U"]', 50, "封面图片")
    if imgEle is None:
        return
    consolewrap("裁剪图片 完成")

    # 描述
    consolewrap("描述")
    if summary != None and len(summary) > 0:
        browser.find_by_id('summary').first.fill(summary)

    # tag
    consolewrap("标签...")
    for i in range(0, len(tags)):
        exist = isElementExist(
            browser, '//div[@class="labelItem___3DGUr" and @data-index="%d"]' % i)
        if not exist:
            browser.find_by_xpath(
                '//a[@class="addLabel___2GuL6"]').first.click()
        # 双击
        browser.find_by_xpath(
            '//div[@class="labelItem___3DGUr" and @data-index="%d"]' % i).first.double_click()
        browser.find_by_xpath(
            '//div[@class="labelItem___3DGUr editlabelItem___3T8AR" and @data-index="%d"]' % i).first.fill(tags[i])

    consolewrap("发布")
    try:
        # TODO 无头模式下，点击【发 布】按钮，报错不可见，但有头就不会
        # 使用js方法执行没问题
        js = 'document.getElementsByClassName("ant-btn ant-btn-primary")[1].click();'
        browser.evaluate_script(js)
    except Exception as e:
        consolewrap("发布失败："+str(e))
        return

    # TODO 最大10个
    consolewrap("发布点击成功")

    # TODO 记录发布的视频
    dbutil.insertVideoLog(
        video.id, Manager.currentUploador.platform_id, Manager.currentUploador.id)
    time.sleep(2)

    consolewrap(title + " 发布成功")


# 登录后存储cookies
def login(name, pwd, browser):
    browser.visit(LoginURL)

    browser.find_by_id("loginForm_phone").first.fill(name)
    if isElementExist(browser, '//a[@class="quickLogin___wzY4O quickPassword___1OC8C"]') == True:
        browser.find_by_xpath(
            '//a[@class="quickLogin___wzY4O quickPassword___1OC8C"]').first.click()
    browser.find_by_id("loginForm_password").first.fill(pwd)
    # 登录
    browser.find_by_xpath('//button[@type="submit"]').first.click()

    time.sleep(1)
    cookies = browser.cookies.all()
    # TODO 多个cookies
    cookieDic = storage.getValue(CookiesKey)
    if cookieDic == None:
        cookieDic = {name: cookies}
    else:
        cookieDic[name] = cookies
    storage.store(CookiesKey, cookieDic)
    consolewrap(name + "登录成功")
    return cookies


# 定时获取文字元素 默认时间20s
def getElementByTextWithTime(browser, title, interval=30):
    text = title + ' 检查元素中..'
    console(text)
    element = None
    for i in range(0, interval):
        console(".")
        try:
            elements = browser.find_by_text(title)
            if len(elements) > 0:
                element = elements[0]
                break
        except Exception as e:
            pass
        time.sleep(1)
    console('\n')
    consolewrap('获取元素成功')
    return element

# 定时获取ID元素 默认时间20s


def getElementByIdWithTime(browser, id, interval=30, title=""):
    text = title + ' 检查元素中..'
    console(text)
    element = None
    for i in range(0, interval):
        console('.')
        try:
            elemens = browser.find_by_id(id)
            if len(elemens) > 0:
                element = elemens[0]
                break
        except Exception as e:
            pass
        time.sleep(1)
    console('\n')
    consolewrap('获取元素成功')
    return element

# 定时获取Xpath元素 默认时间20s


def getElementByXpathWithTime(browser, xpath, interval=30, title=""):
    text = title + ' 检查元素中..'
    console(text)
    element = None
    for i in range(0, interval):
        console('.')
        try:
            elemens = browser.find_by_xpath(xpath)
            if len(elemens) > 0:
                element = elemens[0]
                break
        except Exception as e:
            pass
        time.sleep(1)
    console('\n')
    consolewrap('获取元素成功')
    return element


def is_enabledWithTime(element, interval=30, title=""):
    text = title + ' 判断元素可点击..'
    console(text)
    for i in range(0, interval):
        console('.')
        try:
            if is_enabled(element):
                break
        except Exception as e:
            pass
        time.sleep(1)
    console('\n')
    consolewrap('元素可点击')
    return element

def is_enabled(element):
    return element.is_enabled    

# 判断元素是否存在
def isElementExist(browser, xpath):
    return browser.is_element_present_by_xpath(xpath)


def console(text):
    Manager.consoleWidget.normalOutputWritten(text)


def consolewrap(text):
    Manager.consoleWidget.normalOutputWarp(text)
